package com.quanshu.exchange.ui.gui.message.friends;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.entity.tmp.TmpLabelEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by jye on 2018/1/22.
 */

public class UpdateLabelNameActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.input_text)
    EditText inputText;
    @BindView(R.id.ok_btn)
    Button okBtn;
    private TmpLabelEntity labelEntity;
    private String newLabelName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_label_name);
        ButterKnife.bind(this);
        initIntent();
        initListener();
        initView();
    }

    private void initIntent() {
        labelEntity = (TmpLabelEntity) getIntent().getSerializableExtra("TmpLabelEntity");
    }

    private void initView() {
        if (labelEntity != null) {
            inputText.setText(labelEntity.getLabelName());
            inputText.setSelection(labelEntity.getLabelName().length());
        }
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().afterTextChangeEvents(inputText,
                afterText -> newLabelName = afterText.editable().toString());
        RxViewHelper.getInstance().clicks(okBtn, aVoid -> doCommit());
    }

    private void doCommit() {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .updateFriendLabelName(AppUtils.getSignParams(labelEntity.getLabelId(), newLabelName), labelEntity.getLabelId(), newLabelName)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast("修改成功");
                        Intent intent = getIntent();
                        intent.putExtra("newLabelName", newLabelName);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
    }
}
